package com.sangeng.filter;

import com.sangeng.domain.LoginUser;
import com.sangeng.utils.JwtUtil;
import com.sangeng.utils.RedisCache;
import io.jsonwebtoken.Claims;
import io.lettuce.core.dynamic.annotation.CommandNaming;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author LENOVO
 * @version 1.0
 * @date 2025/6/17 22:04
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        String userId = "";
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }



        //从redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        //将用户信息存入SecurityContextHolder

        //同样需要返回Authentication对象,所以我们也一样分装进UsernamePasswordAuthenticationToken中,他是Authentication的实现类
        //具体可以参考LoginServiceImpl中的loadUserByUsername方法
        //获取权限信息封装到Authentication中
        //参数一：登录用户,参数二：用户密码,参数三：权限信息
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());

        //补充上面UsernamePasswordAuthenticationToken这段的注解
        //虽然 Redis 中没有存储权限信息authorities(被我们用注解标注不序列化了)，但在 LoginUser.getAuthorities() 方法中做了延迟加载处理
        //authorities 没有被序列化进 Redis，只要 permissions 字段存在，就能重新生成权限集合。
        //用户权限从数据库查出，封装为 List<String> permissions
        //存入 Redis 的 LoginUser 对象中包含这个 permissions 字段（未注解排除）
        //此时创建 UsernamePasswordAuthenticationToken 时调用 loginUser.getAuthorities(),因为 permissions 还在所以getAuthorities()内部会自动重建权限集合
        //于是LoginUser中的authorities属性就被赋值了
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request,response);
    }
}